import hashlib
import json
import logging
import os
from base64 import b64decode, b64encode

from configparser import ConfigParser

import yaml
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

from requests import request



class BaseApi:

    def __init__(self):
        self._path = None
        self._response = None
        self._pub_key = None
        self.config = ConfigParser()
        self.config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../datas/config/config.ini")
        self._params = {}

    def send(self, data):
        """发送请求"""
        print(data)
        self._response = request(**data)
        return self._response

    def config_read(self, name, option):
        """读取配置文件"""
        if not os.path.exists:
            raise FileNotFoundError(f"No such file: {self.config_path}")
        self.config.read(self.config_path, encoding="utf-8")
        return self.config.get(name, option)

    def yaml_read(self, yaml_path, name):
        self._path = os.path.join(os.path.dirname(os.path.abspath(__file__)), yaml_path)
        if not os.path.exists:
            raise FileNotFoundError(f"No such file: {self._path}")
        with open(self._path, 'r', encoding="utf-8") as f:
            # 将yaml文件里的模板替换成变量
            fun_data = yaml.safe_load(f)[name]
            raw = json.dumps(fun_data)
        for key, value in self._params.items():
            raw = raw.replace(f"${{{key}}}", value)
        data = json.loads(raw)
        return data

    def crypt(self, password):
        """
        登录前先对密码进行加密操作
        :param password: 需要加密的明文密码
        :return: 加密后的base64密码
        """
        # 将base64公钥字符串进行utf-8编码
        key64 = self.config_read('rsa', 'pub_key').encode()
        key_der = b64decode(key64)
        self._pub_key = RSA.import_key(key_der)
        cipher = PKCS1_v1_5.new(self._pub_key)
        # 把明文密码进行md5加密
        md5 = hashlib.md5()
        md5.update(bytes(password.encode("utf-8")))
        passwd = md5.hexdigest()
        # 将md5加密后得到的密码进行RSA加密
        encrypt_passwd = cipher.encrypt(passwd.encode())
        # 加密完成后进行utf-8解码同时进行base64编码
        new_passwd = b64encode(encrypt_passwd).decode(encoding="utf-8")
        return new_passwd


base = BaseApi()
